
#include "mtime.h"


M3D_BEGIN_NAMESPACE

enum {
    SECS_PER_DAY = 86400,
    MSECS_PER_DAY = 86400000,
    SECS_PER_HOUR = 3600,
    MSECS_PER_HOUR = 3600000,
    SECS_PER_MIN = 60,
    MSECS_PER_MIN = 60000
}; 


MTime MTime::addMSecs(int ms) const
{
    MTime t;
    if (ms < 0) {
        // % not well-defined for -ve, but / is.
        int negdays = (MSECS_PER_DAY - ms) / MSECS_PER_DAY;
        t.mds = (ds() + ms + negdays * MSECS_PER_DAY) % MSECS_PER_DAY;
    } else {
        t.mds = (ds() + ms) % MSECS_PER_DAY;
    }

    return t;
}


int MTime::msecsTo(const MTime &t) const
{
	return t.ds() - ds();
}
 


MTime MTime::currentTime()
{
	MTime ct;

    struct timeval tv;
    gettimeofday(&tv, 0);
    time_t ltime = tv.tv_sec;
    tm *t = 0;

	t = localtime(&ltime);
    ct.mds = MSECS_PER_HOUR * t->tm_hour + MSECS_PER_MIN * t->tm_min + 1000 * t->tm_sec
             + tv.tv_usec / 1000;


	return ct;
}


void MTime::start()
{   
    *this = currentTime();
}   

int MTime::restart()
{
    MTime t = currentTime();
    int n = msecsTo(t);
    if (n < 0)                                // passed midnight
        n += 86400*1000;
    *this = t;
    return n;
}

int MTime::elapsed() const
{
    int n = msecsTo(currentTime());
    if (n < 0)                                // passed midnight
        n += 86400 * 1000;
    return n;
}



M3D_END_NAMESPACE
